package xyz.robinbingo.leetcode.a20.b05.c13;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.IntStream;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
public class Solution1 {
    private Queue<TreeNode> queue = new LinkedList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        bfs(root, result);

        return result;
    }

    private void bfs(TreeNode root, List<List<Integer>> result) {
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> integers = new ArrayList<>();
            IntStream.range(0, size).mapToObj(i -> queue.poll())
                    .forEach(poll -> {
                        integers.add(poll.val);
                        if (poll.left != null) {
                            queue.offer(poll.left);
                        }
                        if (poll.right != null) {
                            queue.offer(poll.right);
                        }
                    });
            result.add(integers);
        }
    }
}